package com.automation.ljf.strategy.impl;

import com.automation.ljf.exception.BizException;
import com.jayway.jsonpath.JsonPath;
import com.automation.ljf.domain.dataobject.CaseStepDO;
import com.automation.ljf.strategy.OperationStrategy;
import com.automation.ljf.util.DriverUtils;
import com.automation.ljf.util.ResultMessage;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.springframework.stereotype.Component;

/**
 * canvas画布元素操作
 *
 * @author lijiefeng
 * @since 2021/9/2
 */
public class CanvasStrategyImpl {

    /**
     * 点击画布元素
     */
    @Component("TO_CANVAS")
    static class ToCanvasStrategy implements OperationStrategy {

        @Override
        public ResultMessage doOperation(ChromeDriver driver, CaseStepDO caseStepDO, String jsonData) {

            String params = null;
            String windowHandle = driver.getWindowHandle();
            try{
                Actions actions = new Actions(driver);
                DriverUtils.timeoutWait(driver, null);
                int xOffset = 0, yOffset = 0;
                if (caseStepDO.getStepJsonpath() != null){
                    params = JsonPath.read(jsonData, caseStepDO.getStepJsonpath());
                    if (params == null){
                        System.out.println("这里空了");
                        throw new BizException(3001, "jsonpath获取值为NULL");
                    }
                    //获取x 和 y坐标值
                    String[] strings = params.split(",");
                    xOffset = Integer.parseInt(strings[0]);
                    yOffset = Integer.parseInt(strings[1]);
                }
                //点击canvas
                actions.moveToElement(driver.findElement(By.xpath(caseStepDO.getStepXpath())), xOffset, yOffset)
                        .click()
                        .release()
                        .perform();
                DriverUtils.timeoutWait(driver, null);
                Thread.sleep(2000);
            }catch (Exception e){
//                throw new BizException(ExceptionEnums.SPECIAL_ERROR);
                return  ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                        .addData("errorMsg", "不可预知的错误")
                        .addData("window", windowHandle);
            }

            return ResultMessage.ok("操作成功").addData("parameter", params);
        }

    }

}
